/**
 * @file   Queue.java
 * @author Enrique Madrid <emadridm@gmail.com>
 * @date   Mon Nov 09 09:57:00 2009
 *
 * @brief Synchronized First Input First Output Vector 
 *
 */

package com.myt.matp.utils;

import java.util.*;

public final class Queue {

    // Object queue size
    private static final int INIT_SIZE = 4;

    // Lock vector for
    private static final int LOCKED_FOR_APPEND = 1;
    private static final int LOCKED_FOR_REMOVE = 2;
    private static final int LOCKED_FOR_DELETE = 3;

    // Queue size
    private Vector m_Vector = null;

    public Queue() {
	m_Vector = new Vector(INIT_SIZE);
    }

    public Queue(int size) {
        m_Vector = new Vector(size);	
    }
    
    private synchronized Object lock(int lockFor, Object obj) {
	Object ret = null;
	switch(lockFor) {
	case Queue.LOCKED_FOR_APPEND:
	    lockedForAppend(obj);
	    break;
	case Queue.LOCKED_FOR_REMOVE:
	    ret = lockedForRemove();
	    break;
	case Queue.LOCKED_FOR_DELETE:
	    lockedForDelete();
	    break;
	}
	return ret;
    }
    
    private void lockedForAppend(Object obj) {
	if (obj != null) {
	    // Append message to the queue
	    m_Vector.addElement(obj);	
	}
    }

    private Object lockedForRemove() {
	Object obj = null;

	if (m_Vector.size() > 0) {
	    obj = (Object)m_Vector.firstElement();
	    m_Vector.removeElement(obj);
	}
	
	return obj;
    }

    private void lockedForDelete() {
        m_Vector.removeAllElements();
    }
    
    public Object get() {
        return lock(Queue.LOCKED_FOR_REMOVE, null);
    }
    
    public void put(Object obj) {
	lock(Queue.LOCKED_FOR_APPEND, obj);
    }

    public void clr() {
	lock(Queue.LOCKED_FOR_DELETE, null);
    }
}
